import 'package:flutter/material.dart';
import 'package:flutter_faster_study/apps/animation_list_demo/data/data.dart';
import 'package:flutter_faster_study/apps/animation_list_demo/model/shop_item_model.dart';

import 'components/shop_item_widget.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final items = List.from(Data.shoppingList);
  final key = GlobalKey<AnimatedListState>();
  List<int> _list = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("动画列表"),
      ),
      body: Column(
        children: [
          Expanded(
            child: AnimatedList(
              key: key,
              initialItemCount: items.length,
              itemBuilder:
                  (BuildContext context, int index, Animation animation) {
                return buildItem(items[index], index, animation);
              },
            ),
          ),
          Container(
            child: buildInsetButton(),
          ),
        ],
      ),
    );
  }

  Widget buildInsetButton() => ElevatedButton(
        child: Text("添加"),
        onPressed: () => insertItem(3, Data.shoppingList.first),
      );

  Widget buildItem(
          ShopItemModel item, int index, Animation<double> animation) =>
      ShopItemWidget(
        item: item,
        animation: animation,
        onClicked: () => removeItem(index),
      );

  void removeItem(int index) {
    final item = items.removeAt(index);
    key.currentState.removeItem(
        index, (context, animation) => buildItem(item, index, animation));
  }

  void insertItem(int index, ShopItemModel item) {
    items.insert(index, item);
    key.currentState.insertItem(index);
  }
}
